/* eslint-disable @typescript-eslint/no-explicit-any */
import { MetadataKey } from './enum';
import { FactoryMap } from './factory';

/**
 * 验证装饰器
 * @param validator
 * @returns
 */
export function Validate(options?: { validator?: (...args: any) => string | boolean }) {
    return function (target: any, _key: string, descriptor: PropertyDescriptor) {
        const oringinMethod = descriptor.value;

        descriptor.value = function (...params: any[]) {
            const token = Reflect.getMetadata(MetadataKey.TOKEN, target.constructor);
            const module = FactoryMap.get(token);
            if (options?.validator) {
                const res = options.validator(params[0]);
                const isStr = typeof res === 'string';
                if (!res || isStr) {
                    const msg = isStr ? res : `Param is not validate!`;
                    module.showMessage?.fail?.(msg);
                    console.error(msg);
                }
            }
            return oringinMethod.apply(this, [...params]);
        };
    };
}
